// 函数组件
import React, { useState, useEffect, useContext } from 'react';
import { Input, Select, DatePicker, Table, Switch, Modal, message, ConfigProvider, Form, Button } from 'antd';
import "./css/Banner.less"
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import { ExclamationCircleFilled } from '@ant-design/icons';
import zh_CN from 'antd/es/locale/zh_CN';
import BannerDialog from './child/BannerDialog';


import getSelectTime from '../../../utils/date';
// 引入请求api等
import { baseUrl, displayCarouselInfo, delBanner, batchDelBanner } from "../../../api/operationApi"

// 表格列表
interface DataType {
    carouselId: number,
    carouselTital: string,
    carouselLocation: number,
    carouselPic: string,
    carouselUpordown: number, // 上架
    carouselUptimeStart: string, //上架时间开始
    carouselIuptimeEnd: string,  // 上架时间结束
    carouselTime: string, // 上架时间
    carouselType: string // 类型
}

// 表单布局
const layout = {
    labelCol: {
        span: 5,
    },
    wrapperCol: {
        span: 16,
    },
};

function Banner() {
    // 表格列
    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'carouselId',
            width: '7%',
            align: 'center'
        },
        {
            title: '轮播标题',
            dataIndex: 'carouselTital',
            align: 'center'
        },
        {
            title: '封面图',
            dataIndex: 'carouselPic',
            align: 'center',
            render: (value, record, index) => {
                return (
                    <img src={baseUrl + value} width={50} height={50} />
                )
            }
        },
        {
            title: '位置',
            dataIndex: 'carouselLocation',
            align: 'center'
        },
        {
            title: '是否上架',
            dataIndex: 'carouselUpordown',
            align: 'center',
            render: (value, record, index) => {
                return (
                    <Switch checked={value == 0 ? false : true} />
                )
            }
        },
        {
            title: '上架时间段',
            align: 'center',
            width: '20%',
            render: (value, record, index) => {
                return (
                    `${record.carouselUptimeStart}~${record.carouselIuptimeEnd}`
                )
            }
        },
        {
            title: '上架时间',
            dataIndex: 'carouselTime',
            align: 'center',
            width: '15%'
        },
        {
            title: '类型',
            dataIndex: 'carouselType',
            align: 'center'
        },
        {
            title: '操作',
            dataIndex: 'operation',
            align: 'center',
            width: '15%',
            render: (value, record) => (
                <div>
                    <button className='edit' onClick={() => clickMod(record)}>编辑</button>
                    <button className='del' onClick={() => clickDel(record)}>删除</button>
                </div>
            ),
        },
    ];

    const [currentPage, setCurrentPage] = useState<number>(1) // 当前页
    const [pageSize, setPageSize] = useState<number>(3)  // 一页条数
    const [count, setCount] = useState<number>() // 总数

    const [keyWord,setKeyWord] = useState<string>()
    const [state,setState] = useState<string>()
    const [upTime,setUpTime] = useState<string>()


    // 表格数据
    const [data, setData] = useState<DataType[]>([])

    // 1、表格渲染数据
    useEffect(() => {
        getData(currentPage,pageSize,keyWord,state,upTime)
    }, [currentPage,pageSize])

    // 1-1 删除当前页最后一项，页码改变
    useEffect(()=>{
        if(currentPage>1 && data.length===0){
            setCurrentPage(currentPage-1)
        }
    },[data])

    // 1-2 获取轮播数据
    async function getData(currentPage:number,pageSize:number,keyWord?:string,state?:string,upTime?:string) {
        let res = await displayCarouselInfo(
            {
                "currentPage": currentPage,
                "keyWord": keyWord,
                "pageSize": pageSize,
                "state":state ,
                "upTime": upTime
            }
        )
        setCount(res.data.total)
        setData(res.data.list)
    }

    // 1-3 改变页码
    const getPageContent = (currentPage: number, pageSize: number) => {
        setCurrentPage(currentPage)
        setPageSize(pageSize)
    }

    // 2、筛选查询部分
    const [form] = Form.useForm();

    // 点击重置,清空
    const reset = () => {
        form.resetFields()
        setKeyWord('')
        setState('')
        setUpTime('')
        getData(currentPage,pageSize)
        message.success('重置成功')
    }

    // 点击筛选
    const filter = async (values: any) => {
        let time: string = ''
        if (values.time) {
            time = getSelectTime(values.time)
        }

        setKeyWord(values.key)
        setState(values.status)
        setUpTime(time)

        // 发起请求
        getData(currentPage,pageSize,values.key,values.status,time)
        message.success('筛选成功')
    }



    // 3、排序方式
    const changeSort = async (e: string) => {
        // 发起请求
        let res = await displayCarouselInfo(
            {
                "currentPage": currentPage,
                "pageSize": pageSize,
                "sortWay": e,
            }

        )
        setData(res.data.list)
    }

    //  4、点击添加，弹出弹框
    const [type, setType] = useState<string>('')
    const [isModalOpen, setIsModalOpen] = useState<boolean>(false); // 对话框是否打开
    const clickAdd = () => {
        setType("add")
        setIsModalOpen(true)
    }

    // 点击修改，传递值
    const [modStuInfo, setModStuInfo] = useState<DataType>()
    const clickMod = (item: DataType): void => {
        setType('mod')
        setModStuInfo(item)
        // 弹框显示
        setIsModalOpen(true)
    }

    // 点击取消
    const close = () => {
        setIsModalOpen(false)
    }

    // 5、删除
    // 5-1、批量删除
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);     // 多选的列

    // 5-2 多选改变的时候
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        setSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection: TableRowSelection<DataType> = {
        selectedRowKeys,
        onChange: onSelectChange,
        selections: [
            Table.SELECTION_ALL,
            Table.SELECTION_INVERT,
            Table.SELECTION_NONE,
            {
                key: 'odd',
                text: 'Select Odd Row',
                onSelect: (changableRowKeys) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changableRowKeys.filter((_, index) => {
                        if (index % 2 !== 0) {
                            return false;
                        }
                        return true;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
            {
                key: 'even',
                text: 'Select Even Row',
                onSelect: (changableRowKeys) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changableRowKeys.filter((_, index) => {
                        if (index % 2 !== 0) {
                            return true;
                        }
                        return false;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
        ],
    }

    // 5-3 发起批量删除请求
    const { confirm } = Modal;
    const batchDel = () => {
        if (selectedRowKeys.length > 0) {
            confirm({
                title: '确定删除所选吗?',
                icon: <ExclamationCircleFilled />,
                content: '删除之后就没了哦~',
                async onOk() {
                    let res = await batchDelBanner(selectedRowKeys)
                    getData(currentPage,pageSize,keyWord,state,upTime)
                    message.success('删除成功')
                },
                onCancel() {
                    message.warning('取消操作')
                },
            });
        } else {
            message.warning('请至少选择一项')
        }
    }

    // 5-4 单个删除请求
    const clickDel = (item: DataType) => {
        console.log('%c' + '=========>', 'color: #886CE4;font-weight:bolder', 'item', item.carouselId);
        confirm({
            title: '确定删除该轮播图吗?',
            icon: <ExclamationCircleFilled />,
            content: '删除之后就没了哦~',
            async onOk() {
                await delBanner({
                    carouselId: item.carouselId
                })
                getData(currentPage,pageSize,keyWord,state,upTime)
                console.log('%c' + '=========>', 'color: #886CE4;font-weight:bolder', 'data', data);
                message.success('删除成功')
            },
            onCancel() {
                message.warning('取消操作')
            },
        });
    }


    return (
        <div className='Banner'>
            {/* 头部 */}
            <div className='page-top'>
                {/*左边标题  */}
                <div className='page-title'>
                    <p>轮播管理</p>
                </div>
            </div>

            {/* 内容区 */}
            <div className='page-context'>
                {/* 查询部分 */}
                <div className='banner-search'>
                    <p className='search-title'>筛选查询</p>
                    <div className='search-input'>
                        <Form
                            {...layout}
                            name="nest-messages"
                            onFinish={filter}
                            form={form}
                            size={'middle'}
                        >

                            <Form.Item name='key' label="关键字" >
                                <Input placeholder='标题关键字' />
                            </Form.Item>

                            <Form.Item name='status' label="状态" >
                                <Select
                                    className='select-shelf'
                                    placeholder="全部"
                                    style={{ width: 120 }}
                                    allowClear
                                    options={[{ value: '1', label: '上架' }, { value: '0', label: '下架' }]}
                                />
                            </Form.Item>

                            <Form.Item name='time' label="上架时间" >
                                <DatePicker placeholder="请选择时间" showTime />
                            </Form.Item>

                            <Form.Item
                                wrapperCol={{
                                    ...layout.wrapperCol,
                                    offset: 8,
                                }}
                                className='search-btn'
                            >
                                <div className='btn'>
                                    <Button onClick={reset} className='reset'>重置</Button>
                                    <Button htmlType="submit" className='filter'>筛选</Button>
                                </div>

                            </Form.Item>
                        </Form>
                    </div>

                </div>

                {/* 数据表格部分 */}
                <div className='data-list'>
                    <div className='list-title'>
                        <p>数据列表</p>
                        <div className='list-operation'>
                            <div className='operation-one'>
                                <p>排序方式</p>
                                <Select
                                    className='select-shelf'
                                    placeholder="全部"
                                    style={{ width: 120 }}
                                    allowClear
                                    options={[{ value: '按时间倒序', label: '按时间倒序' }, { value: '按时间顺序', label: '按时间顺序' }]}
                                    onChange={changeSort}
                                />
                            </div>
                            <div>
                                <button className='batch-del' onClick={batchDel}>批量删除</button>
                                <button className='add' onClick={clickAdd}>添加</button>
                            </div>
                        </div>
                    </div>

                    {/* 表格部分 */}
                    <ConfigProvider locale={zh_CN}>
                        <Table
                            rowSelection={rowSelection}
                            columns={columns}
                            dataSource={data}
                            scroll={{ y: 270 }}
                            rowKey={item => item.carouselId}
                            pagination={{
                                position: ['bottomCenter'],
                                total: count,
                                pageSize: pageSize,
                                onChange: getPageContent,
                                defaultPageSize: 3,
                                pageSizeOptions: [3, 5, 10, 15],
                                showQuickJumper: true,
                                showSizeChanger: true,
                            }}
                        />
                    </ConfigProvider>


                </div>
            </div>

            {/* 弹框 */}
            <BannerDialog currentPage={currentPage} pageSize={pageSize} getData={getData}  isModalOpen={isModalOpen} modStuInfo={modStuInfo} type={type} close={close}></BannerDialog>

        </div>
    )
}

export default Banner